/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.database.aop;

import com.robam.cloud.database.annotation.SelectDataSource;
import com.robam.cloud.database.datasource.DynamicDataSource;
import com.robam.cloud.database.util.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020/7/5 13:39
 * @Version 1.0
 */
@Component
@Aspect
@Slf4j
@Order(-1) //在事务开启前切换数据源，事务开启后将不能切换数据源
public class DynamicDataSourceAspect {
    @Autowired
    DynamicDataSource dynamicDataSource;

    @Pointcut("@annotation(com.robam.cloud.database.annotation.SelectDataSource)")
    public void execute() {
    }

    @Before("execute() && @annotation(selectDataSource)")
    public void changeDataSource(JoinPoint point, SelectDataSource selectDataSource) throws Throwable {
        String db = selectDataSource.db();
        if (!dynamicDataSource.getTargetDataSources().containsKey(db)) {
            DynamicDataSourceContextHolder.restore();
        } else {
            DynamicDataSourceContextHolder.setMyDBType(db);
        }

    }

    @After("execute() && @annotation(selectDataSource)")
    public void restoreDataSource(JoinPoint point, SelectDataSource selectDataSource) {
        DynamicDataSourceContextHolder.restore();
    }
}
